﻿using System;
using System.Web.UI.WebControls;

using EBAYVN.Util ;
using ETRANPORT.Domain;
using ETRANPORT.Web.Common;
using EBAYVN.Dao;
using ETRANPORT.Web.Shared;
using ETRANPORT.Web.UserControls;
using System.Collections.Generic;


namespace ETRANPORT.Web.Forms.DanhMuc
{
    public partial class NhanVien : Authentication
    {
        private readonly NhanVienDao _nvDao = new NhanVienDao();
        private readonly CongViecDao _cvDao = new CongViecDao();




        private Mode UpdateMode
        {
            get
            {
                try
                {
                    if (Session[SessionKey.MODE] != null)
                    {
                        var mode = Convert.ToInt32(Session[SessionKey.MODE]);
                        return (mode == Mode.Update.GetHashCode()) ? Mode.Update : Mode.Create;
                    }

                    return Mode.Create;
                }
                catch (Exception)
                {
                    return Mode.Create;
                }
            }

            set
            {
                Session[SessionKey.MODE] = value.GetHashCode();
            }
        }

        private FilteredMode Filtered
        {
            get
            {
                try
                {
                    if (Session[SessionKey.FILTEREDMODE] != null)
                    {
                        var mode = Convert.ToInt32(Session[SessionKey.FILTEREDMODE]);
                        return (mode == FilteredMode.Filtered.GetHashCode()) ? FilteredMode.Filtered : FilteredMode.None;
                    }

                    return FilteredMode.None;
                }
                catch (Exception)
                {
                    return FilteredMode.None;
                }
            }

            set
            {
                Session[SessionKey.FILTEREDMODE] = value.GetHashCode();
            }
        }

        private NHANVIEN ItemObj
        {
            get
            {
                if (!ValidateData())
                    return null;

                var nv = new NHANVIEN
                             {
                                 MANV = txtMANV.Text.Trim(),
                                 HOTEN =  txtHOTEN.Text.Trim(),
                                 
                                 CMND=txtCMND.Text.Trim(),
                                 EMAIL=txtEmail.Text.Trim(),
                                 DIACHI=txtDIACHI.Text.Trim(),
                             };

                if(!string.IsNullOrEmpty(txtNGAYSINH.Text.Trim()))
                    nv.NGAYSINH = DateTimeUtil.GetVietNamDate(txtNGAYSINH.Text);
                if (!ddlCONGVIEC.SelectedValue.Equals("%"))
                    nv.MACV = ddlCONGVIEC.SelectedValue;
                return nv;
            }
        }




        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                

                if (!Page.IsPostBack)
                {
                    // Bind data for grid view
                    LoadStaticReferences();
                    BindDataForGrid();
                }
            }
            catch (Exception ex)
            {
                DoError(new Message(MessageConstants.E_EXCEPTION, MessageType.Error, ex.Message, ex.StackTrace));
            }
        }

        #region Startup script registeration
        private void SetControlValue(string id, string value)
        {
            ((EOS)Page.Master).SetControlValue(id, value);
        }

        private void SetReadonly(string id, bool isReadonly)
        {
            ((EOS)Page.Master).SetReadonly(id, isReadonly);
        }

        private void ShowError(string message, string controlId)
        {
            ((EOS)Page.Master).ShowError(message, controlId);
        }

        private void ShowError(string message)
        {
            ((EOS)Page.Master).ShowError(message);
        }

        private void ShowInfor(string message)
        {
            ((EOS)Page.Master).ShowInfor(message);
        }

        private void CloseWaitingDialog()
        {
            ((EOS)Page.Master).CloseWaitingDialog();
        }
        #endregion



        
        private void BindDataForGrid()
        {
            if (Filtered == FilteredMode.None)
            {
                var objList = _nvDao.GetList();

                gvList.DataSource = objList;
                gvList.PagerInforText = objList.Count.ToString();
                gvList.DataBind();
            }
            else
            {
                var objList = _nvDao.GetList(txtMANV.Text.Trim(), txtHOTEN.Text.Trim(), ddlCONGVIEC.SelectedValue);

                gvList.DataSource = objList;
                gvList.PagerInforText = objList.Count.ToString();
                gvList.DataBind();
            }
        }
        
        private void LoadStaticReferences()
        {
            var cvList = _cvDao.GetList();
            ddlCONGVIEC.Items.Clear();
            ddlCONGVIEC.Items.Add(new ListItem("Tất cả", "%"));
            foreach (var cv in cvList)
            {
                ddlCONGVIEC.Items.Add(new ListItem(cv.TENCV, cv.MACV));
            }
        }

        private bool ValidateData()
        {
            if (string.Empty.Equals(txtMANV.Text))
            {
                ShowError(String.Format(Resources.Message.E_INVALID_DATA, "Mã nhân viên"), txtMANV.ClientID);
                return false;
            }

            if (string.Empty.Equals(txtHOTEN.Text))
            {
                ShowError(String.Format(Resources.Message.E_INVALID_DATA, "Tên nhân viên"), txtMANV.ClientID);
                return false;
            }
            if (!string.IsNullOrEmpty(txtNGAYSINH.Text.Trim()))
            {
                try
                {
                    DateTimeUtil.GetVietNamDate(txtNGAYSINH.Text);
                }
                catch
                {
                    ShowError(String.Format(Resources.Message.E_INVALID_DATA, "Ngày sinh"), txtNGAYSINH.ClientID);
                    return false;
                }
            }
            
            return true;
        }

        private void ClearForm()
        {
            UpdateMode = Mode.Create;

            txtMANV.Text = "";
            txtMANV.Focus();
            txtMANV.ReadOnly = false;

            txtHOTEN.Text = "";
            ddlCONGVIEC.SelectedIndex = 0;
            txtEmail.Text = "";
            txtCMND.Text = "";
            txtNGAYSINH.Text = "";
            txtDIENTHOAI.Text = "";
            txtDIACHI.Text = "";
        }

        


        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Filtered = FilteredMode.None;
            ClearForm();
            BindDataForGrid();
            upnlGrid.Update();
            CloseWaitingDialog();
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            var nv = ItemObj;
            if (nv == null)
            {
                CloseWaitingDialog();
                return;
            }

            Message msg;
            Filtered = FilteredMode.None;

            // insert new
            if (UpdateMode == Mode.Create)
            {
                if (!HasInsertPermission)
                {
                    CloseWaitingDialog();
                    ShowInfor(Resources.Message.WARN_PERMISSION_DENIED);
                    return;
                }

                var tontai = _nvDao.Get(txtMANV.Text.Trim());
                if (tontai != null)
                {
                    CloseWaitingDialog();
                    ShowError("Mã nhân viên đã tồn tại", txtMANV.ClientID);
                    return;
                }

                msg = _nvDao.Insert(nv);
            }
            else
            {
                if (!HasUpdatePermission)
                {
                    CloseWaitingDialog();
                    ShowInfor(Resources.Message.WARN_PERMISSION_DENIED);
                    return;
                }
                
                msg = _nvDao.Update(nv);
            }

            CloseWaitingDialog();

            if (msg == null) return;

            if (msg.MsgType != MessageType.Error)
            {
                ShowInfor(ResourceLabel.Get(msg));

                ClearForm();
                BindDataForGrid();

                upnlGrid.Update();
            }
            else
            {
                ShowError(ResourceLabel.Get(msg));
            }
        }
        
        protected void btnFilter_Click(object sender, EventArgs e)
        {
            Filtered = FilteredMode.Filtered;
            BindDataForGrid();

            upnlGrid.Update();
            CloseWaitingDialog();
        }
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            try
            {
                // Authenticate
                if (!HasDeletePermission)
                {
                    CloseWaitingDialog();
                    ShowError(Resources.Message.WARN_PERMISSION_DENIED);
                    return;
                }
                var strIds = Request["listIds"];
                if ((strIds != null) && (!string.Empty.Equals(strIds)))
                {
                    var listIds = strIds.Split(',');

                    // Kiem tra relation ship truoc khi delete
                    string flag = "";
                    foreach (var ma in listIds)
                    {
                        if (_nvDao.IsInUse(ma))
                        {
                            var msgIsInUse = new Message(MessageConstants.E_OBJECT_IN_USED, MessageType.Info, "Nhân viên với mã", ma);
                            ShowError(ResourceLabel.Get(msgIsInUse));
                            CloseWaitingDialog();
                            return;
                        }
                        var nv = _nvDao.Get(ma);
                        if (nv != null)
                        {
                            var msg = _nvDao.Delete(nv);
                            if (msg.MsgType == MessageType.Error)
                            {
                                flag += msg.ToString();
                                break;
                            }
                        }
                    }
                    if (string.IsNullOrEmpty(flag))
                    {
                        ShowInfor("Xóa Nhân Viên thành Công");
                    }
                    else
                    {
                        ShowError(flag);
                    }
                }
                BindDataForGrid();
                upnlGrid.Update();
                CloseWaitingDialog();

            }
            catch (Exception ex)
            {
                DoError(new Message(MessageConstants.E_EXCEPTION, MessageType.Error, ex.Message, ex.StackTrace));
            }
        }




        private void BindItem(NHANVIEN obj)
        {
            if (obj == null)
                return;

            SetControlValue(txtMANV.ClientID, obj.MANV);
            SetReadonly(txtMANV.ClientID, true);
            SetControlValue(txtHOTEN.ClientID, obj.HOTEN);
            var cv = ddlCONGVIEC.Items.FindByValue(obj.MACV);
            if (cv != null)
                ddlCONGVIEC.SelectedIndex = ddlCONGVIEC.Items.IndexOf(cv);
            SetControlValue(txtNGAYSINH.ClientID, obj.NGAYSINH.HasValue ? obj.NGAYSINH.Value.ToString("dd/MM/yyyy") : "");
            SetControlValue(txtDIACHI.ClientID, obj.DIACHI);
            SetControlValue(txtDIENTHOAI.ClientID, obj.DIENTHOAI);
            SetControlValue(txtEmail.ClientID, obj.EMAIL);
            SetControlValue(txtCMND.ClientID, obj.CMND);
            upnlInfor.Update();
        }

        protected void gvList_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                var id = e.CommandArgument.ToString();

                switch (e.CommandName)
                {
                    case "EditItem":
                        var objDb = _nvDao.Get(id);

                        if(objDb != null)
                        {
                            BindItem(objDb);
                            UpdateMode = Mode.Update;
                        }

                        CloseWaitingDialog();

                        break;
                }
            }
            catch (Exception ex)
            {
                DoError(new Message(MessageConstants.E_EXCEPTION, MessageType.Error, ex.Message, ex.StackTrace));
            }
        }
    }
}